<template>
  <div>
    <van-address-edit
      :area-list="areaList"
      :address-info="addressInfo"
      show-postal
      show-delete
      show-set-default
      show-search-result
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
      @change-area="changeArea"
    />
  </div>
</template>

<script>
import { areaList } from "@vant/area-data";
import { getAddress, editAddress, delAddress } from "@/api";

export default {
  data() {
    return {
      areaList,
      searchResult: [],
      addressInfo: {},
      areaCode: "",
    };
  },
  methods: {
    // 获取完整地址编码
    changeArea(value) {
      this.areaCode = value.map((item) => item.code).join("-");
    },

    async onSave(value) {
      value.country = value.county;
      value.areaCode = this.areaCode;
      let data = await editAddress(this.$route.params.id, value);
      let { status, message } = data;
      if (!status) {
        this.$router.back();
      }
      this.$toast(message);
      let result = await getAddress();
      result.forEach((item) => {
        if (item.id === this.$store.state.address.id) {
          this.$store.commit("setAddress", item);
        }
      });
    },
    async onDelete() {
      let data = await delAddress(this.$route.params.id);
      let { status, message } = data;
      if (!status) {
        this.$router.back();
      }
      this.$toast(message);
      // 删除再获取地址列表进行判断
      let addresslist = await getAddress();
      // 如果地址列表为空，就清空Vuex中的地址
      if (addresslist.length === 0) {
        this.$store.commit("setAddress", []);
        return;
      }

      if (this.$store.state.address.id !== this.addressInfo.id) {
        return;
      }
      // 如果删除的地址是Vuex里面的地址，就取默认的地址存放到Vuex，如果没有默认地址就取第一个地址存到Vuex
      let defaultAddress = addresslist.filter((item) => {
        return item.isDefault == true;
      });
      if (defaultAddress.length > 0) {
        this.$store.commit("setAddress", defaultAddress[0]);
      } else {
        this.$store.commit("setAddress", addresslist[0]);
      }
    },
  },
  async mounted() {
    let data = await getAddress();
    let result = data.filter((item) => {
      return item.id == this.$route.params.id;
    });
    this.areaCode = result[0].areaCode;
    result[0].county = result[0].country;
    result[0].areaCode = result[0].areaCode.split("-")[2];
    this.addressInfo = result[0];
  },
};
</script>
